#coding=utf-8
import datetime
import stutils
stutils.set_django_environ()
from djstock.shstock.models import *

'''
每天可能发生stock info的更改：
1 新股发行
2 名称改变
3 流通A股数量改变(eg: 大非、小非解禁)
so we have to update db table stcode 、share、tradableshare everyday.
'''

def stcode2db():
    cns = scraper.get_shstcode()
    
    for c,n in cns:
        try:
            isValidStcode(c)
        except ValidationError,e:
            print e
            continue
        else:
            Stcode.objects.get_or_create(code=c,name=n)


def create_a_share(code):
    '''从stcode表中获得相应stock最新的code、name,
    建立or update相应的object in Share db'''
    #从stcode表中获得相应stock最新的code、name
    try:
        s_instcode = Stcode.objects.filter(code=code).latest('created_at')
    except Stcode.DoesNotExist,e:
        print "No Share whose code is %s in db stcode"%code
        return
    n = s_instcode.name

    #if 相应stock已经存在, check if name changed.
    try:
        s = Share.objects.get(code=code)
    except Share.DoesNotExist,e:
        pass
    else:
        if s.name != n:
            s.name = n 
            s.save()
        return s

    #no?create a new share    
    i = scraper.get_ipo(code)
    try:
        isValidExdate(i)
    except ValidationError,e:
        print code, 'has valid ipo date.'
        print e
        return
    
    s = Share(code=code, name=n, ipo=i)
    s.save()
    return s 

def shares2db():
    codes = list(set([s.code for s in Stcode.objects.all()]))
    codes.sort()      
    for c in codes:
        s = create_a_share(c)
        if not s:
            print 'sth wrong about %s'%c
        s.ts2db()
        print s 
        
def updateinfo():
    info = []
    td = datetime.date.today().isoformat()
    info.append( "今天:%s\n"%td )

    q1 = Stcode.objects.filter(created_at=td)
    info.append('表stcode 新增加%s条记录.\n'%str(q1.count()))
    for c in q1:
        code = c.code
        
        q2 = Stcode.objects.filter(code=code)
        if q2.count() == 1:
            info.append('add new stock:%s'%str(c))
        else:
            old = q2.order_by('-created_at')[1]
            info.append( '%s --> %s'%( str(old), str(c) ) )
        
    info.append("以下是流通A股数量更改的情况:")        
    q3 = TradableShare.objects.filter(created_at=td) 
    for ts in q3:
        s = ts.share
        new = str( ts.quantity )
        
        q4 = s.tradableshare_set.all()
        if q4.count() == 1:
            info.append('new stock %s 的流通A股数量:%s'%(str(s), new))
        else:
            old = str( q4.order_by('-created_at')[1].quantity )
            info.append( "%s:%s --> %s"%(str(s),old,new) )
              
    return '\n'.join( info )

def updatehsl(ts):
    '''当流通A股数量发生更改后,相应时间内的Price data 也要发生改变.'''
    share = ts.share
    
    start_date = ts.date
    td = datetime.date.today().isoformat()
    if start_date > td:
        print "今天是%s. %s will change 流通A股数量 in the future(%s)"%(td, share, start_date)
        return 
    else:
        print "%s will update its 换手率 since %s"%(share, start_date)
    
    eds = share.exday_set.filter(date_gte=start_date)
    for e in eds:
        p = e.price
        p.hsl = p.get_hsl()
        p.save()
        
if __name__ == '__main__':
    #update db Table stcode
    stcode2db()
    print 'update stcode ok.'
    
    #update db Table share and tradableshare
    shares2db()
    
    print updateinfo()
